package com.seek.inter;

import com.alibaba.fastjson.JSON;
import com.seek.service.BlacklistService;
import com.seek.util.BankNameUtil;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.seek.authcheck.constants.AuthConstant;
import com.seek.cache.CacheUtil;
import com.seek.common.handler.SpringContextHolder;
import com.seek.constants.ApiParamsConstant;
import com.seek.inter.interdto.InterDtoCUser;
import com.seek.model.dto.ResultInfo;
import com.seek.model.entity.TCustomer;
import com.seek.service.CustomerCertifyService;
import com.seek.service.CustomerMobileInfoService;
import com.seek.service.CustomerService;
import com.seek.service.CustomerZfbService;
import com.seek.service.InterService;
import com.seek.util.CommonUtil;
import com.seek.util.ConstantsUtil;
import com.seek.util.JsonUtil;
import com.seek.util.MD5Util;
import com.seek.util.SmsCodeCacheUtil;
import com.seek.util.UUIDUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * app客户帐号相关接口
 */
public class CustomerInter {
  private static final Logger logger = LoggerFactory.getLogger(CustomerInter.class);

  private CustomerService customerService = (CustomerService) SpringContextHolder
      .getBean("customerService");
  private InterService interService = (InterService) SpringContextHolder.getBean("interService");

  private CustomerCertifyService customerCertifyService = (CustomerCertifyService) SpringContextHolder
      .getBean("customerCertifyService");

  private CustomerMobileInfoService customerMobileInfoService = (CustomerMobileInfoService) SpringContextHolder
      .getBean("customerMobileInfoService");

  private CustomerZfbService customerZfbService = (CustomerZfbService) SpringContextHolder
      .getBean("customerZfbService");

  private BlacklistService blacklistService = (BlacklistService) SpringContextHolder
      .getBean("blacklistService");

  /**
   * 登录
   */
  public ResultInfo login(HttpServletRequest request, JSONObject reqJson) throws Exception {
    ResultInfo result = new ResultInfo();
    String phoneNo = reqJson.getString("phoneNo");
    String password = reqJson.getString("password");
    String clientid = reqJson.getString("clientid");
    String companyId = reqJson.getString("companyId");

    // 检查传入的参数
    if (CommonUtil.isEmpty(phoneNo) || CommonUtil.isEmpty(password)) {
      result.setStatus(1);
      result.setMessage("参数不完整，请检查！");
      return result;
    }
    password = MD5Util.MD5(password + phoneNo.substring(6)).toLowerCase();

    // 根据手机号取得客户资料
    Map<String, Object> data = customerService.getBaseCustomerInfo(companyId, phoneNo);
    if (data == null || data.get("custId") == null) {
      result.setStatus(1);
      result.setMessage("您尚未注册，请先完成注册！");
      return result;
    }
    // 校验密码是否一致
    if (!password.equals(data.get("password"))) {
      result.setStatus(1);
      result.setMessage("密码错误，请重新输入！");
      return result;
    }
    data.put("password", null);
    // 更新客户的最近登录日期，手机登录设备号，激活日期（如果原来未激活的话）
    String updateSql = null;
    if (data.get("activeDate") == null) {
      if (data.get("agentId") == null) {
        updateSql = "update t_customer set last_login_time=now(),client_id=?,active_date=now() where id=?";
        customerService.executeUpdate(updateSql, new Object[]{clientid, data.get("custId")});
      } else {
        // 处理代理商分润并激活
        customerService.activeCustomer("" + data.get("custId"), clientid, "" + data.get("agentId"),
            "" + data.get("subAgentId"));
      }
    } else {
      if (CommonUtil.isEmpty(clientid)) {
        updateSql = "update t_customer set last_login_time=now() where id=?";
        customerService.executeUpdate(updateSql, new Object[]{data.get("custId")});
      } else {
        updateSql = "update t_customer set last_login_time=now(),client_id=? where id=?";
        customerService.executeUpdate(updateSql, new Object[]{clientid, data.get("custId")});
      }
    }

    // 把登录用户记入缓存
    data.put("clientid", clientid);
    String token = UUIDUtil.getUUID();
    data.put("token", token);
    CacheUtil.putRedisCUser(token, JsonUtil.toJson(data));
    String oldToken = CacheUtil.getRedisData("COUSTOMER_TOKEN_" + data.get("custId"));
    if (!CommonUtil.isEmpty(oldToken)) {
      CacheUtil.delRedisData(oldToken);
    }
    CacheUtil.putRedisData("COUSTOMER_TOKEN_" + data.get("custId"), token);

    // 显示的银行卡号要显示为带*号
    String cardNo = "" + data.get("cardNumber");
    if (!CommonUtil.isEmpty(cardNo)){
    	cardNo = "**** **** **** " + cardNo.substring(cardNo.length() - 4);
    	data.put("cardNumber", cardNo);
    }
    
    result.setStatus(0);
    result.setMessage("成功");
    result.setBody(data);
    return result;
  }

  /**
   * 注册
   */
  public ResultInfo register(HttpServletRequest request, JSONObject reqJson) throws Exception {
    ResultInfo result = new ResultInfo();
    String companyId = reqJson.getString("companyId");
    String agentId = reqJson.getString("agentId");
    String fagentId = reqJson.getString("fagentId");
    String phoneNo = reqJson.getString("phoneNo");
    String verificationCode = reqJson.getString("verificationCode");
    String password = reqJson.getString("password");
    String clientid = reqJson.getString("clientid");

    // 检查传入的参数
    if (CommonUtil.isEmpty(phoneNo) || CommonUtil.isEmpty(password) || CommonUtil
        .isEmpty(verificationCode)) {
      result.setStatus(1);
      result.setMessage("参数不完整，请检查！");
      return result;
    }
    // 检测验证码
    if (!SmsCodeCacheUtil.checkSms(phoneNo, verificationCode)) {
      result.setStatus(2);
      result.setMessage("验证码输入错误或已失效！");
      return result;
    }
    //判断是否在黑名单内
    if(blacklistService.existPhone(phoneNo)){
      result.setStatus(3);
      result.setMessage("该手机号在系统黑名单内，无法注册！");
      return result;
    }

    // 判断用户是否已存在
    if (customerService.checkPhoneExists(phoneNo, null)) {
      result.setStatus(3);
      result.setMessage("该手机号已注册，请使用其它手机号注册！");
      return result;
    }
    password = MD5Util.MD5(password + phoneNo.substring(6)).toLowerCase();
    // 添加会员的保存
    TCustomer en = new TCustomer();
    en.setCompanyId(CommonUtil.getLongValue(companyId));
    en.setPhoneNo(phoneNo);
    en.setPassword(password);
    en.setStatus(ConstantsUtil.CUSTOMER_STATUS_UNCERTIFY);
    en.setCertificationStatus(0);
    en.setCardBindStatus(0);
    en.setAddrbookStatus(0);
    en.setMobileStatus(0);
    en.setZfbStatus(0);
    en.setHasElinkman(0);
    en.setRegDate(new Date());
    en.setClientId(clientid);
    en.setIsBlack(0);
    en.setAuthedCredit(0);
    // 如果是网页注册，则必然会有agentid，此时不能激活
    if (CommonUtil.getLongValue(agentId) > 0) {
      if (CommonUtil.getLongValue(fagentId) > 0) {
        en.setAgentId(CommonUtil.getLongValue(fagentId));
        en.setSubAgentId(CommonUtil.getLongValue(agentId));
      } else {
        en.setAgentId(CommonUtil.getLongValue(agentId));
      }
    } else {
      // 直接注册直接激活，不用处理代理商佣金
      en.setActiveDate(new Date());
      en.setLastLoginTime(new Date());
    }
    en = customerService.save(en);

    // 设置返回：如果是非网页登录，则需要直接登录:
    Map<String, Object> data = null;
    if (en.getAgentId() == null || en.getAgentId() <= 0) {
      data = customerService.getBaseCustomerInfo(companyId, phoneNo);
      data.put("password", null);

      // 把登录用户记入缓存
      String token = UUIDUtil.getUUID();
      data.put("token", token);
      data.put("clientid", clientid);
      CacheUtil.putRedisCUser(token, JsonUtil.toJson(data));
      CacheUtil.putRedisData("COUSTOMER_TOKEN_" + data.get("custId"), token);
    }

    result.setStatus(0);
    result.setMessage("成功");
    result.setBody(data);
    return result;
  }

  /**
   * 通过验证码重置密码
   */
  public ResultInfo resetPassword(HttpServletRequest request, JSONObject reqJson) throws Exception {
    ResultInfo result = new ResultInfo();
    String companyId = reqJson.getString("companyId");
    String phoneNo = reqJson.getString("phoneNo");
    String verificationCode = reqJson.getString("verificationCode");
    String password = reqJson.getString("password");

    // 检查传入的参数
    if (CommonUtil.isEmpty(phoneNo) || CommonUtil.isEmpty(password) || CommonUtil
        .isEmpty(verificationCode)) {
      result.setStatus(1);
      result.setMessage("参数不完整，请检查！");
      return result;
    }
    password = MD5Util.MD5(password + phoneNo.substring(6)).toLowerCase();
    // 检测验证码
    if (!SmsCodeCacheUtil.checkSms(phoneNo, verificationCode)) {
      result.setStatus(2);
      result.setMessage("验证码输入错误或已失效！");
      return result;
    }
    // 判断用户是否已存在
    if (!customerService.checkPhoneExists(phoneNo, null)) {
      result.setStatus(3);
      result.setMessage("该手机号尚未注册，请先完成注册！");
      return result;
    }

    // 更新客户的手机号
    String sql = "update t_customer set password=? where company_id=? and phone_no=?";
    interService.executeUpdate(sql, new Object[]{password, companyId, phoneNo});

    result.setStatus(0);
    result.setMessage("成功");
    return result;
  }

  /**
   * 修改密码
   */
  public ResultInfo modifyCustPassword(HttpServletRequest request, JSONObject reqJson)
      throws Exception {
    ResultInfo result = new ResultInfo();
    String oldPassword = reqJson.getString("oldPassword");
    String password = reqJson.getString("newPassword");

    // 检查传入的参数
    if (CommonUtil.isEmpty(password) || CommonUtil.isEmpty(oldPassword)) {
      result.setStatus(1);
      result.setMessage("参数不完整，请检查！");
      return result;
    }

    // 更新客户的密码，通过返回值判断是否更新成功
    // 根据token取得客户的ID
    String token = reqJson.getString("token");
    InterDtoCUser en = CacheUtil.getCLoginCache(token);
    if (en == null) {
      result.setStatus(1);
      result.setMessage("您尚未登录，请先登录花金宝！");
      return result;
    }
    oldPassword = MD5Util.MD5(oldPassword + en.getPhoneNo().substring(6)).toLowerCase();
    password = MD5Util.MD5(password + en.getPhoneNo().substring(6)).toLowerCase();
    String sql = "update t_customer set password=? where id=? and password=?";
    int ret = interService.executeUpdate(sql, new Object[]{password, en.getCustId(), oldPassword});
    if (ret < 1) {
      result.setStatus(1);
      result.setMessage("密码更新失败，您的旧密码输入错误！");
      return result;
    }
    result.setStatus(0);
    result.setMessage("成功");
    return result;
  }

  /**
   * 更新客户头像
   */
  public ResultInfo updateCustHeadimg(HttpServletRequest request, JSONObject reqJson)
      throws Exception {
    ResultInfo result = new ResultInfo();
    String custId = reqJson.getString("custId");
    String headimgUrl = reqJson.getString("headimgUrl");

    // 检查传入的参数
    if (CommonUtil.isEmpty(headimgUrl) || CommonUtil.getLongValue(custId) < 1) {
      result.setStatus(1);
      result.setMessage("参数不完整，请检查！");
      return result;
    }

    String sql = "update t_customer set headimg_url=? where id=?";
    interService.executeUpdate(sql, new Object[]{headimgUrl, custId});
    Map<String, Object> m = new HashMap<String, Object>();
    m.put("headimgUrl", headimgUrl);
    CacheUtil.refreshCustRedis(reqJson.getString("token"), m);

    result.setStatus(0);
    result.setMessage("成功");
    return result;
  }

  /**
   * 查询客户基本信息
   */
  public ResultInfo getCustInfo(HttpServletRequest request, JSONObject reqJson) throws Exception {
    ResultInfo result = new ResultInfo();
    String token = request.getParameter(ApiParamsConstant.TOKEN);
    InterDtoCUser cuser = CacheUtil.getCLoginCache(token);
    String custId = cuser.getCustId();
    // 检查传入的参数
    if (CommonUtil.getLongValue(custId) < 1) {
      result.setStatus(1);
      result.setMessage("参数不完整，请检查！");
      return result;
    }

    String sql = "select  * from  t_customer where id = ?";
    List<TCustomer> customers = customerService.findBySql(sql, new Object[]{custId});
    if (CollectionUtils.isNotEmpty(customers) && customers.size() == 1) {
      result.setStatus(0);
      result.setMessage("成功");
      result.setBody(customers.get(0));
    } else {
      result.setStatus(1);
      result.setMessage("没有查询到客户信息");
    }

    return result;
  }

  /**
   * 查询客户认证信息
   */
  public ResultInfo getCustAuthInfo(HttpServletRequest request, JSONObject reqJson)
      throws Exception {
    ResultInfo result = new ResultInfo();
    Long custId = CommonUtil.getLongValue(reqJson.getString(ApiParamsConstant.CUST_ID));
    Long companyId = CommonUtil.getLongValue(reqJson.getString(ApiParamsConstant.COMPANY_ID));
    Map<String, Object> data = new HashMap<>();

    String sql =
        "select  name ,ifnull(card_number,'')  as idCard,ifnull(certification_status,0) as certStatus,"
            + "ifnull(card_bind_status,0) as cardStatus,ifnull(mobile_status,0) as carrierStatus ,ifnull(zfb_status,0)"
            + " as zfbStatus from t_customer where id = ? and company_id = ?";
    Map<String, Object> customer = customerService
        .findOneMapBySql(sql, new Object[]{custId, companyId});
    logger.info("basecustomerinfo:{}",JSON.toJSONString(customer));
    if (MapUtils.isNotEmpty(customer)) {
      Integer certStatus = CommonUtil.getIntValue(customer.get("certStatus"));
      Integer cardStatus = CommonUtil.getIntValue(customer.get("cardStatus"));
      Integer carrierStatus = CommonUtil.getIntValue(customer.get("carrierStatus"));
      Integer zfbStatus = CommonUtil.getIntValue(customer.get("zfbStatus"));
      String certificationStatus =
          certStatus + "." + cardStatus + "." + carrierStatus + "." + zfbStatus;
      data.put("certificationStatus", certificationStatus);
      /**********身份认证信息**********/
      if (null != certStatus && certStatus != AuthConstant.AUTH_NONE) {
        String certSql = "select DATE_FORMAT(submit_time,'%Y-%m-%d') as commitTime,"
            + "DATE_FORMAT(audit_time,'%Y-%m-%d %H:%i:%s') as successTime,card_valid as cardValid, "
            + "audit_status as auditStatus,audit_remark as auditRemark from t_customer_certify where company_id = ? and customer_id = ?";


        Map<String, Object> realAuth = customerService
            .findOneMapBySql(certSql, new Object[]{companyId, custId});

        String cardNo = customer.get("idCard").toString();
//        if (StringUtils.isNotEmpty(cardNo)) {
//          int len = cardNo.length();
//          cardNo = len == 18 ? StringUtils.substring(cardNo, 0, 10) + "****" + StringUtils
//              .substring(cardNo, len - 4)
//              : StringUtils.substring(cardNo, 0, 8) + "****" + StringUtils
//                  .substring(cardNo, len - 3);
//        }
        if (MapUtils.isNotEmpty(realAuth)) {
          realAuth.put("name", customer.get("name"));
          realAuth.put("idCard", cardNo);
          int auditStatus = CommonUtil.getIntValue(realAuth.get("auditStatus"));
          if (auditStatus== 2 || auditStatus==3) {
            data.put("authFaildResult", realAuth.get("auditRemark"));
          }
        } else {
          if (certStatus == AuthConstant.AUTH_FAIL) {
            data.put("authFaildResult", "网络错误");

          }
        }
        data.put("realAuth", realAuth);
      }

      /**********银行卡认证信息**********/
      if (null != cardStatus && cardStatus != AuthConstant.AUTH_NONE) {
        String cardSql = "select DATE_FORMAT(submit_time,'%Y-%m-%d') as addTime,"
            + "DATE_FORMAT(audit_time,'%Y-%m-%d %H:%i:%s') as commitTime, ifnull(card_number,'') as cardNo, "
            + "bank_name as bankName ,audit_status as auditStatus ,audit_remark as auditRemark from "
            + "t_customer_card where company_id = ? and customer_id = ? and history = ? ";
//        Map<String, Object> bankAuth = null;
        Map<String, Object> bankAuth = customerService
            .findOneMapBySql(cardSql, new Object[]{companyId, custId, 0});

        if (MapUtils.isNotEmpty(bankAuth)) {
          String cardNo = bankAuth.get("cardNo").toString();
          String bankName = BankNameUtil.getBankName(String.valueOf(bankAuth.get("bankName")));
          String bankInfo = StringUtils.isNotEmpty(bankName) ? CacheUtil.getRedisData(bankName) : "";
          if(StringUtils.isNotEmpty(bankInfo)){
            JSONObject bankJson = JSON.parseObject(bankInfo);
            String logoUrl =bankJson.getString("typeLogo");
            bankAuth.put("logoUrl",logoUrl);
          }
          bankAuth.put("bankName",bankName);
          if (StringUtils.isNotEmpty(cardNo)) {
            int len = cardNo.length();
            cardNo =  "**** **** **** "+StringUtils.substring(cardNo, len - 4);
            bankAuth.put("cardNo", cardNo);
          }
          int auditStatus = CommonUtil.getIntValue(bankAuth.get("auditStatus"));
          if (auditStatus== 2 || auditStatus==3) {
            data.put("authFaildResult", bankAuth.get("auditRemark"));
          }

        } else {
          if (cardStatus == AuthConstant.AUTH_FAIL) {
            data.put("authFaildResult", "网络错误");

          }
        }
        data.put("bankAuth", bankAuth);
      }

      /**********运营商认证信息**********/
      if (null != carrierStatus && carrierStatus != AuthConstant.AUTH_NONE) {
        String carrierSql =
            "select DATE_FORMAT(last_modify_time,'%Y-%m-%d') as commitTime,"
                + "DATE_FORMAT(last_modify_time,'%Y-%m-%d %H:%i:%s') as successTime,phone_no as phoneNo, "
                + "audit_status as auditStatus ,audit_remark as auditRemark from t_customer_mobile_info "
                + "where company_id = ? and customer_id = ? ";

        Map<String, Object> carrierAuth = customerMobileInfoService
            .findOneMapBySql(carrierSql, new Object[]{companyId, custId});
        if (MapUtils.isNotEmpty(carrierAuth)) {
          int auditStatus = CommonUtil.getIntValue(carrierAuth.get("auditStatus"));
          if (auditStatus== 2 || auditStatus==3) {
            data.put("authFaildResult", carrierAuth.get("auditRemark"));
          }
        } else {
          if (carrierStatus == AuthConstant.AUTH_FAIL) {
            data.put("authFaildResult", "网络错误");
          }
        }
        data.put("carrierAuth", carrierAuth);
      }
      /**********支付宝认证信息**********/
      if (null != zfbStatus && zfbStatus != AuthConstant.AUTH_NONE) {
        String alipaySql =
            "select DATE_FORMAT(submit_time,'%Y-%m-%d') as commitTime,"
                + "DATE_FORMAT(audit_time,'%Y-%m-%d %H:%i:%s') as successTime,login_name as alipayAccount, "
                + "audit_status as auditStatus,audit_remark as auditRemark  from t_customer_zfb"
                + " where company_id = ? and customer_id = ? and lsbz = ?";

        Map<String, Object> alipayAuth = customerZfbService
            .findOneMapBySql(alipaySql,
                new Object[]{companyId, custId, 0});

        if (MapUtils.isNotEmpty(alipayAuth)) {
          int auditStatus = CommonUtil.getIntValue(alipayAuth.get("auditStatus"));
          if (auditStatus== 2 || auditStatus==3) {
            data.put("authFaildResult", alipayAuth.get("auditRemark"));
          }
        } else {
          if (zfbStatus == AuthConstant.AUTH_FAIL) {
            data.put("authFaildResult", "网络错误");
          }
        }
        data.put("alipayAuth", alipayAuth);
      }

      result.setBody(data);

    } else {
      result.setStatus(1);
      result.setMessage("没有查询到客户信息");
    }
    result.setStatus(0);
    result.setMessage("操作成功!");
    return result;
  }


  /**
   * 根据token获取客户基本资料
   */
  public ResultInfo getCustInfoByToken(HttpServletRequest request, JSONObject reqJson)
      throws Exception {
    ResultInfo result = new ResultInfo();
    String token = reqJson.getString("token");
    InterDtoCUser cuser = CacheUtil.getCLoginCache(token);
    
    if (cuser != null){
    	String cardNo = cuser.getCardNumber();
        if (!CommonUtil.isEmpty(cardNo)){
        	cardNo = "**** **** **** " + cardNo.substring(cardNo.length() - 4);
        	cuser.setCardNumber(cardNo);
        }
    }
    
    result.setStatus(0);
    result.setMessage("成功");
    result.setBody(cuser);

    return result;
  }
}
